import { NextRequest, NextResponse } from 'next/server';
import { Document, Paragraph, HeadingLevel, Packer } from 'docx';
import UserModel from '@/models/user';

export async function GET(request: NextRequest) {
  try {
    // 从URL参数中获取用户ID
    const url = new URL(request.url);
    const userId = url.searchParams.get('userId');
    
    if (!userId) {
      return NextResponse.json({ error: '缺少用户ID参数' }, { status: 400 });
    }
    
    // 获取用户信息
    const user = await UserModel.findById(parseInt(userId));
    if (!user) {
      return NextResponse.json({ error: '用户不存在' }, { status: 404 });
    }
    
    // 创建一个非常简单的Word文档
    const doc = new Document({
      sections: [{
        properties: {},
        children: [
          new Paragraph({
            text: `${user.username} 的简历`,
            heading: HeadingLevel.TITLE,
          }),
          new Paragraph({
            text: `邮箱: ${user.email}`,
          }),
          new Paragraph({
            text: `电话: ${user.phone || '未提供'}`,
          }),
          new Paragraph({
            text: `所在地: ${user.location || '未提供'}`,
          }),
          new Paragraph({
            text: `这是一个测试简历，生成于 ${new Date().toLocaleString()}`,
          }),
        ],
      }],
    });
    
    // 生成Word文档的Buffer
    const buffer = await Packer.toBuffer(doc);
    
    // 设置响应头，使浏览器下载文件
    const headers = new Headers();
    headers.set('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
    headers.set('Content-Disposition', `attachment; filename=${encodeURIComponent(user.username)}_resume_test.docx`);
    
    return new NextResponse(buffer, {
      status: 200,
      headers,
    });
    
  } catch (error) {
    console.error('导出简历错误:', error);
    return NextResponse.json(
      { error: '导出简历失败，请稍后再试', details: error instanceof Error ? error.message : '未知错误' },
      { status: 500 }
    );
  }
}
